﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PMisuseAn.io;
using System.Collections.Specialized;
using System.Collections;
using PMisuseAn.util;

namespace PMisuseAn
{
    /// <summary>
    /// Interaction logic for AddPolicyWindow1.xaml
    /// </summary>
    public partial class AddPolicyWindow1 : Window
    {
        ContextInterface ci_ = null;
        //public static string formula_ = "";

        List<Attribute> agentAttributes;
        List<Attribute> functionalAttributes;
        List<Attribute> environmentalAttributes;
        List<Attribute> regulatoryAttributes;

        List<string> groupNames;
        List<string> actorNames;

        private ListDictionary if_rc_formula = new ListDictionary();
        private ListDictionary if_then_rc_formula = new ListDictionary();
        private ListDictionary if_then_unless_rc_formula = new ListDictionary();

        private ListDictionary do_rc_formula = new ListDictionary();
        private ListDictionary do_until_rc_formula = new ListDictionary();
        private ListDictionary do_until_unless_rc_formula = new ListDictionary();

        private int comp_id = 1;

        bool isAgentAttSelected = false;
        bool isFunctionalAttSelected = false;
        bool isEnvironmentalAttSelected = false;
        bool isRegulatoryAttSelected = false;
        bool isActorRoleSelected = false;
        bool isGroupSelected = false;
        bool isGroupFunctionSelected = false;

        List<string> agents;

        Attribute selectedAttribute;

        bool if_rule_active = false;

        bool functionalSpecComplete = true;
        bool groupfunctionalSpecComplete = true;

        List<string> functionalParameters = new List<string>();
        List<string> groupFunctionalParameters = new List<string>();
        
        public AddPolicyWindow1()
        {
            InitializeComponent();
            this.Left = 20;
            this.Top = 25;

            agentAttributes = new List<Attribute>();
            functionalAttributes = new List<Attribute>();
            regulatoryAttributes = new List<Attribute>();
            environmentalAttributes = new List<Attribute>();
            actorNames = new List<string>();
            groupNames = new List<string>();

            loadAttributesToCategoryList();
            reloadPolicyStatementsTable();
            loadRoles_lb();
            //loadActorsToComboBox();
            loadGroupsToCategoryList();
            reloadGroupFunction_lb();
            reloadPolicyFunction_lb();


            agents = MisUseAnObjectsDB.loadAllAgentNames(MainWindow.clusterName);

            reInitialiseRuleCategoryComp();
            reinitialiseActiveInactiveComps();
        }

        public AddPolicyWindow1(ContextInterface ci)
        {
            InitializeComponent();
            ci_ = ci;
            this.Left = 20;
            this.Top = 25;

            agentAttributes = new List<Attribute>();
            functionalAttributes = new List<Attribute>();
            regulatoryAttributes = new List<Attribute>();
            environmentalAttributes = new List<Attribute>();
            actorNames = new List<string>();
            groupNames = new List<string>();

            loadAttributesToCategoryList();
            reloadPolicyStatementsTable();
            loadGroupsToCategoryList();
            //loadActorsToComboBox();
            reloadGroupFunction_lb();
            reloadPolicyFunction_lb();
            loadRoles_lb();

            agents = MisUseAnObjectsDB.loadAllAgentNames(MainWindow.clusterName);

            reInitialiseRuleCategoryComp();
            reinitialiseActiveInactiveComps();
        }

        List<string> noOpenSym = new List<string>();

        private void autoCloseSymbols()
        {
            foreach (var x in noOpenSym)
            {
                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(") ");
                    if_rc_formula.Add("symbol_" + comp_id, ")");
                    comp_id = comp_id + 1;

                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(") ");
                    if_then_rc_formula.Add("symbol_" + comp_id, ") ");
                    comp_id = comp_id + 1;

                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(") ");
                    if_then_unless_rc_formula.Add("symbol_" + comp_id, ") ");
                    comp_id = comp_id + 1;
                }
            }
            noOpenSym = new List<string>();

            //not.IsEnabled = true;
            or.IsEnabled = true;
            and.IsEnabled = true;
        }

        private void Symbol_Auto_Close_Button_Click(object sender, RoutedEventArgs e)
        {
            autoCloseSymbols();
        }        

        private void Symbol_Button_Click(object sender, RoutedEventArgs e)
        {
            Button symbol_b = (Button)sender;
            string symbol = (string)symbol_b.Content;

            
            if (symbol != null)
            {
                if (symbol.Equals("¬") || symbol.Equals("∧") || symbol.Equals("V"))
                {
                    if (noOpenSym.Count > 0)
                    {
                        if (if_rc_rb.IsChecked == true)
                        {
                            if_rc_tb.AppendText(") ");
                            if_rc_formula.Add("symbol_" + comp_id, ") ");
                            comp_id = comp_id + 1;

                            if_rc_tb.AppendText(symbol + " ");
                            if_rc_formula.Add("symbol_" + comp_id, symbol);
                            comp_id = comp_id + 1;

                            if_rc_tb.AppendText("( ");
                            if_rc_formula.Add("symbol_" + comp_id, "( ");
                            comp_id = comp_id + 1;
                        }
                        else if (if_then_rc_rb.IsChecked == true)
                        {
                            if_then_rc_tb.AppendText(") ");
                            if_then_rc_formula.Add("symbol_" + comp_id, ") ");
                            comp_id = comp_id + 1;

                            if_then_rc_tb.AppendText(symbol + " ");
                            if_then_rc_formula.Add("symbol_" + comp_id, symbol);
                            comp_id = comp_id + 1;

                            if_then_rc_tb.AppendText("( ");
                            if_then_rc_formula.Add("symbol_" + comp_id, "( ");
                            comp_id = comp_id + 1;
                        }
                        else if (if_then_unless_rc_rb.IsChecked == true)
                        {
                            if_then_unless_rc_tb.AppendText(") ");
                            if_then_unless_rc_formula.Add("symbol_" + comp_id, ") ");
                            comp_id = comp_id + 1;

                            if_then_unless_rc_tb.AppendText(symbol + " ");
                            if_then_unless_rc_formula.Add("symbol_" + comp_id, symbol);
                            comp_id = comp_id + 1;

                            if_then_unless_rc_tb.AppendText("( ");
                            if_then_unless_rc_formula.Add("symbol_" + comp_id, "( ");
                            comp_id = comp_id + 1;
                        }
                    }
                    else
                    {
                        if (if_rc_rb.IsChecked == true)
                        {
                            if_rc_tb.AppendText(symbol + " ");
                            if_rc_formula.Add("symbol_" + comp_id, symbol);
                            comp_id = comp_id + 1;

                            if_rc_tb.AppendText("( ");
                            if_rc_formula.Add("symbol_" + comp_id, "( ");
                            comp_id = comp_id + 1;
                        }
                        else if (if_then_rc_rb.IsChecked == true)
                        {
                            if_then_rc_tb.AppendText(symbol + " ");
                            if_then_rc_formula.Add("symbol_" + comp_id, symbol);
                            comp_id = comp_id + 1;

                            if_then_rc_tb.AppendText("( ");
                            if_then_rc_formula.Add("symbol_" + comp_id, "( ");
                            comp_id = comp_id + 1;
                        }
                        else if (if_then_unless_rc_rb.IsChecked == true)
                        {
                            if_then_unless_rc_tb.AppendText(symbol + " ");
                            if_then_unless_rc_formula.Add("symbol_" + comp_id, symbol);
                            comp_id = comp_id + 1;

                            if_then_unless_rc_tb.AppendText("( ");
                            if_then_unless_rc_formula.Add("symbol_" + comp_id, "( ");
                            comp_id = comp_id + 1;
                        }

                        noOpenSym.Add("(");
                    }
                }
                else
                {
                    if (if_rc_rb.IsChecked == true)
                    {
                        if_rc_tb.AppendText(symbol + " ");
                        if_rc_formula.Add("symbol_" + comp_id, symbol);
                        comp_id = comp_id + 1;
                    }
                    else if (if_then_rc_rb.IsChecked == true)
                    {
                        if_then_rc_tb.AppendText(symbol + " ");
                        if_then_rc_formula.Add("symbol_" + comp_id, symbol);
                        comp_id = comp_id + 1;
                    }
                    else if (if_then_unless_rc_rb.IsChecked == true)
                    {
                        if_then_unless_rc_tb.AppendText(symbol + " ");
                        if_then_unless_rc_formula.Add("symbol_" + comp_id, symbol);
                        comp_id = comp_id + 1;
                    }
                }
                
                activeInactiveCompsSymbolSelection(symbol);
            }
        }

        private void Clear_Button_Click(object sender, RoutedEventArgs e)
        {
            clearAll();
        }

        private void clearAll()
        {
            clearFormulaBox();

            isAgentAttSelected = false;
            isFunctionalAttSelected = false;
            isEnvironmentalAttSelected = false;
            isRegulatoryAttSelected = false;
            isActorRoleSelected = false;
            isGroupSelected = false;
            isGroupFunctionSelected = false;

            functionalSpecComplete = true;
            functionalParameters = new List<string>();
            noOpenSym = new List<string>();
            
            do_rc_formula.Clear();
            do_until_rc_formula.Clear();
            do_until_unless_rc_formula.Clear();
            if_rc_formula.Clear();
            if_then_rc_formula.Clear();
            if_then_unless_rc_formula.Clear();

            domain_l_t.Content = "";
            value_cb.Items.Clear();
            comp_id = 1;

            reInitialiseRuleCategoryComp();
        }

        private void clearFormulaBox()
        {
            if_rc_rb.IsChecked = false;
            if_rc_tb.Document = new FlowDocument();
            if_then_rc_rb.IsChecked = false;
            if_then_rc_tb.Document = new FlowDocument();
            if_then_unless_rc_rb.IsChecked = false;
            if_then_unless_rc_tb.Document = new FlowDocument();
            then_temporal_cb.SelectedIndex = 4;
            unless_temporal_cb.SelectedIndex = 4;

            reinitialiseActiveInactiveComps();
        }

        private void reInitialiseRuleCategoryComp()
        {
            if_rc_rb.IsEnabled = true;

            if_then_rc_rb.IsEnabled = false;
            if_then_unless_rc_rb.IsEnabled = false;
            then_temporal_cb.IsEnabled = false;
            unless_temporal_cb.IsEnabled = false;

            if_rc_tb.IsEnabled = false;
            if_then_rc_tb.IsEnabled = false;
            if_then_unless_rc_tb.IsEnabled = false;
        }

        public void loadRoles_lb()
        {           
            actor_roles_lb.Items.Add("sender");
            actor_roles_lb.Items.Add("receiver");
            actor_roles_lb.Items.Add("subject");

        }

        //private void actorsList_cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    string actorName = actorsList_cb.SelectedItem.ToString();
        //    List<string> actorRoles = MisUseAnObjectsDB.loadActorRoles(actorName, MainWindow.clusterName);
        //    actor_roles_lb.ItemsSource = actorRoles;
        //    actor_roles_lb.IsEnabled = true;

        //    isActorRoleSelected = false;
        //}

        public void loadGroupsToCategoryList()
        {
            groupNames = MisUseAnObjectsDB.loadAllGroupNamesDB(MainWindow.clusterName);
            groups_lb.ItemsSource = groupNames;
            isGroupSelected = false;
        }

        public void loadAttributesToCategoryList()
        {
            List<string> agentAttributes_s = new List<string>();
            List<string> functionalAttributes_s = new List<string>();
            List<string> environmentalAttributes_s = new List<string>();
            List<string> regulatoryAttributes_s = new List<string>();

            agentAttributes = MisUseAnObjectsDB.loadAgentAttributes(MainWindow.clusterName);
            //functionalAttributes = MisUseAnObjectsDB.loadFunctionalAttributes(MainWindow.clusterName);
            environmentalAttributes = MisUseAnObjectsDB.loadEnvironmentAttributes(MainWindow.clusterName);
            regulatoryAttributes = MisUseAnObjectsDB.loadRegulatoryAttributes(MainWindow.clusterName);

            foreach (Attribute att in agentAttributes)
            {
                agentAttributes_s.Add(att.name);
            }
            agentAttributes_lb.ItemsSource = agentAttributes_s;

            //foreach (Attribute att in functionalAttributes)
            //{
            //    functionalAttributes_s.Add(att.name);
            //}
            //functionalAttributes_lb.ItemsSource = functionalAttributes_s;

            foreach (Attribute att in environmentalAttributes)
            {
                environmentalAttributes_s.Add(att.name);
            }
            environmentAttributes_lb.ItemsSource = environmentalAttributes_s;

            foreach (Attribute att in regulatoryAttributes)
            {
                regulatoryAttributes_s.Add(att.name);
            }
            regulatoryAttributes_lb.ItemsSource = regulatoryAttributes_s;

            isAgentAttSelected = false;
            isFunctionalAttSelected = false;
            isEnvironmentalAttSelected = false;
            isRegulatoryAttSelected = false;
        }

        public void reinitialiseActiveInactiveComps()
        {
            if (functionalSpecComplete == false || groupfunctionalSpecComplete == false)
            {
                return;
            }

            if (if_rc_rb.IsChecked == true | if_then_rc_rb.IsChecked == true |
                if_then_unless_rc_rb.IsChecked == true )
            {
                lessthan.IsEnabled = false;
                greaterthan.IsEnabled = false;
                equals.IsEnabled = false;
                notequals.IsEnabled = false;
                //properSubset.IsEnabled = false;
                //subset.IsEnabled = false;
                //union.IsEnabled = false;
                //intersection.IsEnabled = false;
                //elementOf.IsEnabled = false;
                //notElementof.IsEnabled = false;
                //not.IsEnabled = true;
                or.IsEnabled = true;
                and.IsEnabled = true;
                //implies.IsEnabled = false;
                //openingBracket.IsEnabled = true;
                //closingBracket.IsEnabled = false;
                plus.IsEnabled = false;
                minus.IsEnabled = false;
                multiplication.IsEnabled = false;
                division.IsEnabled = false;
                value_cb.IsEnabled = false;
                att_value_ok.IsEnabled = false;

                agentAttributes_lb.IsEnabled = true;
                environmentAttributes_lb.IsEnabled = true;
                functionalAttributes_lb.IsEnabled = true;
                regulatoryAttributes_lb.IsEnabled = true;
                actor_roles_lb.IsEnabled = true;
                groups_lb.IsEnabled = true;
                group_functions_lb.IsEnabled = true;
            }
            else
            {
                lessthan.IsEnabled = false;
                greaterthan.IsEnabled = false;
                equals.IsEnabled = false;
                notequals.IsEnabled = false;
                //properSubset.IsEnabled = false;
                //subset.IsEnabled = false;
                //union.IsEnabled = false;
                //intersection.IsEnabled = false;
                //elementOf.IsEnabled = false;
                //notElementof.IsEnabled = false;
                //not.IsEnabled = false;
                or.IsEnabled = false;
                and.IsEnabled = false;
                //implies.IsEnabled = false;
                //openingBracket.IsEnabled = false;
                //closingBracket.IsEnabled = false;
                plus.IsEnabled = false;
                minus.IsEnabled = false;
                multiplication.IsEnabled = false;
                division.IsEnabled = false;
                value_cb.IsEnabled = false;
                att_value_ok.IsEnabled = false;

                agentAttributes_lb.IsEnabled = false;
                environmentAttributes_lb.IsEnabled = false;
                functionalAttributes_lb.IsEnabled = false;
                regulatoryAttributes_lb.IsEnabled = false;
                actor_roles_lb.IsEnabled = false;
                //actor_roles_lb.ItemsSource = new List<string>();
                groups_lb.IsEnabled = false;
                group_functions_lb.IsEnabled = false;

            }          
        }

        public void activeInactiveCompsSymbolSelection(String symbol)
        {
            if (functionalSpecComplete == false || groupfunctionalSpecComplete == false)
            {
                return;
            }

            if (if_rc_rb.IsChecked == true | if_then_rc_rb.IsChecked == true |
                if_then_unless_rc_rb.IsChecked == true)
           {
                agentAttributes_lb.IsEnabled = true;
                regulatoryAttributes_lb.IsEnabled = true;
                environmentAttributes_lb.IsEnabled = true;
                functionalAttributes_lb.IsEnabled = true;
                actor_roles_lb.IsEnabled = true;
                groups_lb.IsEnabled = true;
                group_functions_lb.IsEnabled = true;

                lessthan.IsEnabled = false;
                greaterthan.IsEnabled = false;
                equals.IsEnabled = true;
                notequals.IsEnabled = true;
                //properSubset.IsEnabled = false;
                //subset.IsEnabled = false;
                //union.IsEnabled = false;
                //intersection.IsEnabled = false;
                //elementOf.IsEnabled = false;
                //notElementof.IsEnabled = false;
                //not.IsEnabled = true;
                or.IsEnabled = true;
                and.IsEnabled = true;
                //implies.IsEnabled = false;
                //openingBracket.IsEnabled = true;
                //closingBracket.IsEnabled = true;
                plus.IsEnabled = false;
                minus.IsEnabled = false;
                multiplication.IsEnabled = false;
                division.IsEnabled = false;
                value_cb.IsEnabled = true;
                att_value_ok.IsEnabled = true;
            }
            else
            {
                agentAttributes_lb.IsEnabled = false;
                regulatoryAttributes_lb.IsEnabled = false;
                environmentAttributes_lb.IsEnabled = false;
                functionalAttributes_lb.IsEnabled = false;
                actor_roles_lb.IsEnabled = false;
                //actor_roles_lb.ItemsSource = new List<string>();
                groups_lb.IsEnabled = false;
                group_functions_lb.IsEnabled = false;

                lessthan.IsEnabled = false;
                greaterthan.IsEnabled = false;
                equals.IsEnabled = false;
                notequals.IsEnabled = false;
                //properSubset.IsEnabled = false;
                //subset.IsEnabled = false;
                //union.IsEnabled = false;
                //intersection.IsEnabled = false;
                //elementOf.IsEnabled = false;
                //notElementof.IsEnabled = false;
                //not.IsEnabled = false;
                or.IsEnabled = false;
                and.IsEnabled = false;
                //implies.IsEnabled = false;
                //openingBracket.IsEnabled = false;
                //closingBracket.IsEnabled = true;
                plus.IsEnabled = false;
                minus.IsEnabled = false;
                multiplication.IsEnabled = false;
                division.IsEnabled = false;
                value_cb.IsEnabled = false;
                att_value_ok.IsEnabled = false;
            }            
        }

        public void activeInactiveCompsSymbolSelection()
        {
            if (functionalSpecComplete == false || groupfunctionalSpecComplete == false)
            {
                return;
            }

            if (if_rc_rb.IsChecked == true | if_then_rc_rb.IsChecked == true |
                if_then_unless_rc_rb.IsChecked == true )                
            {
                agentAttributes_lb.IsEnabled = true;
                environmentAttributes_lb.IsEnabled = true;
                regulatoryAttributes_lb.IsEnabled = true;
                functionalAttributes_lb.IsEnabled = true;
                actor_roles_lb.IsEnabled = true;
                groups_lb.IsEnabled = true;
                group_functions_lb.IsEnabled = true;

                lessthan.IsEnabled = false;
                greaterthan.IsEnabled = false;
                equals.IsEnabled = true;
                notequals.IsEnabled = true;
                //properSubset.IsEnabled = false;
                //subset.IsEnabled = false;
                //union.IsEnabled = false;
                //intersection.IsEnabled = false;
                //elementOf.IsEnabled = false;
                //notElementof.IsEnabled = false;
                //not.IsEnabled = true;
                or.IsEnabled = true;
                and.IsEnabled = true;
                //implies.IsEnabled = false;
                //openingBracket.IsEnabled = true;
                //closingBracket.IsEnabled = true;
                plus.IsEnabled = false;
                minus.IsEnabled = false;
                multiplication.IsEnabled = false;
                division.IsEnabled = false;
                value_cb.IsEnabled = true;
                att_value_ok.IsEnabled = true;
            }
            else
            {
                agentAttributes_lb.IsEnabled = false;
                environmentAttributes_lb.IsEnabled = false;
                regulatoryAttributes_lb.IsEnabled = false;
                functionalAttributes_lb.IsEnabled = false;
                actor_roles_lb.IsEnabled = false;
                //actor_roles_lb.ItemsSource = new List<string>();
                groups_lb.IsEnabled = false;
                group_functions_lb.IsEnabled = false;

                lessthan.IsEnabled = false;
                greaterthan.IsEnabled = false;
                equals.IsEnabled = false;
                notequals.IsEnabled = false;
                //properSubset.IsEnabled = false;
                //subset.IsEnabled = false;
                //union.IsEnabled = false;
                //intersection.IsEnabled = false;
                //elementOf.IsEnabled = false;
                //notElementof.IsEnabled = false;
                //not.IsEnabled = true;
                or.IsEnabled = true;
                and.IsEnabled = true;
                //implies.IsEnabled = false;
                //openingBracket.IsEnabled = false;
                //closingBracket.IsEnabled = false;
                plus.IsEnabled = false;
                minus.IsEnabled = false;
                multiplication.IsEnabled = false;
                division.IsEnabled = false;
                value_cb.IsEnabled = false;
                att_value_ok.IsEnabled = false;
            }
        }
        
        private void add_policy_statement_b_Click(object sender, RoutedEventArgs e)
        {

            string transmissionPrinciple = "";
            if (confidentiality.IsChecked == true)
                transmissionPrinciple = "confidentiality";
            else if (secrecy.IsChecked == true)
                transmissionPrinciple = "secrecy";
            else if (consent.IsChecked == true)
                transmissionPrinciple = "consent";
            else if (notice.IsChecked == true)
                transmissionPrinciple = "notice";
            else if (reciprocity.IsChecked == true)
                transmissionPrinciple = "reciprocity";
            else if (desert.IsChecked == true)
                transmissionPrinciple = "desert";
            //else if (compulsion.IsChecked == true)
            //    transmissionPrinciple = "compulsion";
            else if (fiduciary.IsChecked == true)
                transmissionPrinciple = "fiduciary";                
            else if (no_tp.IsChecked == true)
                transmissionPrinciple = "Null"; 
            
            string formula_statement = "";
            if (if_rc_tb.Document != null && if_rule_active ==true)
            {
                TextRange textRange = new TextRange(if_rc_tb.Document.ContentStart,
                if_rc_tb.Document.ContentEnd);
                string formula_statement_sub = textRange.Text;
                formula_statement_sub = formula_statement_sub.TrimEnd('\n');
                formula_statement_sub = formula_statement_sub.TrimEnd('\r');

                //if (missingBracket_if_rc_formula(formula_statement_sub) == true)
                //{
                //    MessageBox.Show("Missing bracket(s) in if rule...", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
                //    return;
                //}
                if (formula_statement_sub.Length > 0)
                {
                    formula_statement = formula_statement + "IF [ " + formula_statement_sub + " ] ";
                }
            }

            bool then_exist = false;
            if (if_then_rc_tb.Document != null && if_rule_active == true)
            {
                TextRange textRange = new TextRange(if_then_rc_tb.Document.ContentStart,
                if_then_rc_tb.Document.ContentEnd);
                string formula_statement_sub = textRange.Text;
                formula_statement_sub = formula_statement_sub.TrimEnd('\n');
                formula_statement_sub = formula_statement_sub.TrimEnd('\r');

                //if (missingBracket_if_then_rc_formula(formula_statement_sub) == true)
                //{
                //    MessageBox.Show("Missing bracket(s) in then rule...", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
                //    return;
                //}

                if (formula_statement_sub.Length > 0)
                {
                    ComboBoxItem cbi = (ComboBoxItem)then_temporal_cb.SelectedItem;
                    string then_temp_const = (string)cbi.Content;
                    formula_statement = formula_statement + "THEN "+then_temp_const+" [ " + formula_statement_sub + " ] ";
                    then_exist = true;
                }
            }

            if (then_exist == false && if_rule_active == true)
            {
                MessageBox.Show("Missing then rule...", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            if (if_then_unless_rc_tb.Document != null && if_rule_active == true)
            {
                TextRange textRange = new TextRange(if_then_unless_rc_tb.Document.ContentStart,
                if_then_unless_rc_tb.Document.ContentEnd);
                string formula_statement_sub = textRange.Text;
                formula_statement_sub = formula_statement_sub.TrimEnd('\n');
                formula_statement_sub = formula_statement_sub.TrimEnd('\r');

                //if (missingBracket_if_then_unless_rc_formula(formula_statement_sub) == true)
                //{
                //    MessageBox.Show("Missing bracket(s) in unless rule...", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
                //    return;
                //}
                if (formula_statement_sub.Length > 0)
                {
                    ComboBoxItem cbi = (ComboBoxItem)unless_temporal_cb.SelectedItem;
                    string unless_temp_const = (string)cbi.Content;
                    formula_statement = formula_statement + "UNLESS "+unless_temp_const+" [ " + formula_statement_sub + " ] ";
                }
            }
           
            if (formula_statement.Length > 0)
            {
                MisUseAnObjectsDB.addPolicyStatement(formula_statement, transmissionPrinciple, MainWindow.clusterName);
                reloadPolicyStatementsTable();
                clearFormulaBox();
                clearAll();

                isAgentAttSelected = false;
                isFunctionalAttSelected = false;
                isRegulatoryAttSelected = false;
                isEnvironmentalAttSelected = false;
                isActorRoleSelected = false;
                isGroupSelected = false;
                isGroupFunctionSelected = false;

                activeInactiveCompsSymbolSelection();
            }
        }

        private void reloadPolicyStatementsTable()
        {
            List<Policy> policy_statements = MisUseAnObjectsDB.loadAllPolicyStatementsFull(MainWindow.clusterName);

            if (policy_statements != null)
            {
                policies_lb.Items.Clear();
                int pol_no = 1;

                foreach (Policy policy in policy_statements)
                {
                    ListBoxItem l = new ListBoxItem();
                    l.FontSize = 10.5;
                    StackPanel s = new StackPanel();
                    s.Orientation = System.Windows.Controls.Orientation.Horizontal;

                    ContentPresenter c1 = new ContentPresenter();
                    c1.Content = pol_no +".";
                    pol_no = pol_no + 1;

                    ContentPresenter c2 = new ContentPresenter();
                    c2.Content = " [TP:" + policy.transmissionPrinciple + "]";

                    ContentPresenter c3 = new ContentPresenter();

                    if (!policy.statement.Equals("DO[NILL]"))
                    {
                        ListBox lb2 = new ListBox();
                        lb2.FontSize = 10.5;

                        PolicyStatementAnalyser psa = new PolicyStatementAnalyser();
                        psa.ifThenUnlessTokenisation(policy.statement);

                        ListBoxItem lb2l1 = new ListBoxItem();
                        string if_content = "IF" + psa.if_content;
                        lb2l1.Content = if_content;
                        lb2.Items.Add(lb2l1);
                        ListBoxItem lb2l2 = new ListBoxItem();
                        string then_content = "   THEN" + psa.then_content;
                        lb2l2.Content = then_content;
                        lb2.Items.Add(lb2l2);
                        if (psa.unless_content != null)
                        {
                            ListBoxItem lb2l3 = new ListBoxItem();
                            string unless_content = "   UNLESS" + psa.unless_content;
                            lb2l3.Content = unless_content;
                            lb2.Items.Add(lb2l3);
                        }

                        if (policies_lb.Items.Count % 2 == 0)
                        {
                            l.Background = Brushes.AliceBlue;

                            lb2.Background = Brushes.AliceBlue;
                            lb2.BorderBrush = Brushes.AliceBlue;
                        }
                        else
                        {
                            lb2.BorderBrush = Brushes.White;
                        }
                        c3.Content = lb2;
                    }
                    else
                    {
                        c3.Content = policy.statement;
                        if (policies_lb.Items.Count % 2 == 0)
                        {
                            l.Background = Brushes.AliceBlue;
                            l.Foreground = Brushes.DarkRed;
                        }
                    }
                    
                    c1.Width = 15;
                    c2.Width = 98;
                    c3.Width = policies_lb.Width - 140;
                    s.Children.Add(c1);
                    s.Children.Add(c2);
                    s.Children.Add(c3);

                    //add context menu to item to clone state machine
                    //use cloneStateMachineDB method in DB class

                    ContextMenu cm = new System.Windows.Controls.ContextMenu();
                    cm.Height = 64;
                    cm.Width = 136;

                    MenuItem cm_d = new MenuItem();
                    cm_d.Header = "Delete";
                    cm_d.Tag = policy;
                    cm_d.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(del_policy_statement_b_Click));
                    cm_d.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    cm_d.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                    cm_d.FontSize = 12;
                    cm_d.Foreground = Brushes.DarkGreen;

                    BitmapImage cm_d_image = new BitmapImage();
                    cm_d_image.BeginInit();
                    Uri cm_d_Uri = new Uri("/PMisuseAn;component/images/DeleteHS.png", UriKind.RelativeOrAbsolute);
                    cm_d_image.UriSource = cm_d_Uri;
                    cm_d_image.EndInit();

                    Image cm_d_iconImage = new Image();
                    cm_d_iconImage.Source = cm_d_image;
                    cm_d.Icon = cm_d_iconImage;

                    cm.Items.Add(cm_d);
                    l.ContextMenu = cm;

                    l.Content = s;
                    l.Tag = policy;

                    policies_lb.Items.Add(l);
                }
            }
        }

        void del_policy_statement_b_Click(object sender, RoutedEventArgs e)
        {
            MessageBoxResult result = MessageBox.Show("Confirm delete...", "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.No)
            {
                return;
            }
            MenuItem d_b = (MenuItem)sender;
            Policy tag_id = (Policy)d_b.Tag;

            MisUseAnObjectsDB.deletePolicyStatement(tag_id.statement, tag_id.transmissionPrinciple, MainWindow.clusterName);
            reloadPolicyStatementsTable();
        } 

        public bool missingBracket_if_rc_formula(string formula_statement_sub)
        {
            int open_bracket = 0;
            int close_bracket = 0;
            foreach (DictionaryEntry f_s in if_rc_formula)
            {
                if (f_s.Value != null && f_s.Value.Equals("("))
                {
                    open_bracket = open_bracket + 1;
                }
                else if (f_s.Value != null && f_s.Value.Equals(")"))
                {
                    close_bracket = close_bracket + 1;
                }
            }
            if (close_bracket == open_bracket)
            {
                return false;
            }
            return true;
        }

        public bool missingBracket_if_then_rc_formula(string formula_statement_sub)
        {
            int open_bracket = 0;
            int close_bracket = 0;
            foreach (DictionaryEntry f_s in if_then_rc_formula)
            {
                if (f_s.Value.Equals("("))
                {
                    open_bracket = open_bracket + 1;
                }
                else if (f_s.Value.Equals(")"))
                {
                    close_bracket = close_bracket + 1;
                }
            }
            if (close_bracket == open_bracket)
            {
                return false;
            }
            return true;
        }

        public bool missingBracket_if_then_unless_rc_formula(string formula_statement_sub)
        {
            int open_bracket = 0;
            int close_bracket = 0;
            foreach (DictionaryEntry f_s in if_then_unless_rc_formula)
            {
                if (f_s.Value.Equals("("))
                {
                    open_bracket = open_bracket + 1;
                }
                else if (f_s.Value.Equals(")"))
                {
                    close_bracket = close_bracket + 1;
                }
            }
            if (close_bracket == open_bracket)
            {
                return false;
            }
            return true;
        }

        public bool missingBracket_do_rc_formula(string formula_statement_sub)
        {
            int open_bracket = 0;
            int close_bracket = 0;
            foreach (DictionaryEntry f_s in do_rc_formula)
            {
                if (f_s.Value.Equals("("))
                {
                    open_bracket = open_bracket + 1;
                }
                else if (f_s.Value.Equals(")"))
                {
                    close_bracket = close_bracket + 1;
                }
            }
            if (close_bracket == open_bracket)
            {
                return false;
            }
            return true;
        }

        public bool missingBracket_do_until_rc_formula(string formula_statement_sub)
        {
            int open_bracket = 0;
            int close_bracket = 0;
            foreach (DictionaryEntry f_s in do_until_rc_formula)
            {
                if (f_s.Value.Equals("("))
                {
                    open_bracket = open_bracket + 1;
                }
                else if (f_s.Value.Equals(")"))
                {
                    close_bracket = close_bracket + 1;
                }
            }
            if (close_bracket == open_bracket)
            {
                return false;
            }
            return true;
        }

        public bool missingBracket_do_until_unless_rc_formula(string formula_statement_sub)
        {
            int open_bracket = 0;
            int close_bracket = 0;
            foreach (DictionaryEntry f_s in do_until_unless_rc_formula)
            {
                if (f_s.Value.Equals("("))
                {
                    open_bracket = open_bracket + 1;
                }
                else if (f_s.Value.Equals(")"))
                {
                    close_bracket = close_bracket + 1;
                }
            }
            if (close_bracket == open_bracket)
            {
                return false;
            }
            return true;
        }


        private void regulatoryAttributes_lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (regulatoryAttributes_lb.SelectedItem == null)
            {
                return;
            }
            string selected_regulatory_att = regulatoryAttributes_lb.SelectedItem.ToString();
            if (functionalSpecComplete == true && groupfunctionalSpecComplete == true)
            {
                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_regulatory_att + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_regulatory_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_regulatory_att + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_regulatory_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_regulatory_att + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_regulatory_att);
                    comp_id = comp_id + 1;
                }

                string attribute_domain = "";
                List<string> att_dom_names = new List<string>();
                foreach (Attribute att in regulatoryAttributes)
                {
                    if (att.name.Equals(selected_regulatory_att))
                    {
                        selectedAttribute = att;
                        isRegulatoryAttSelected = true;
                        isAgentAttSelected = false;
                        isFunctionalAttSelected = false;
                        isEnvironmentalAttSelected = false;
                        isActorRoleSelected = false;
                        isGroupSelected = false;
                        isGroupFunctionSelected = false;

                        //int i = 0;
                        foreach (string s in att.domain)
                        {
                            att_dom_names.Add(s);
                        }
                        break;
                    }
                }
                domain_l_t.Content = attribute_domain + " " + selectedAttribute.literalType;
                reloadDomainInComboBox(att_dom_names);
                activeInactiveCompsLBSelection();
            }
            else if (functionalSpecComplete == true && groupfunctionalSpecComplete == false)
            {
                MessageBox.Show(this, "group expected.",
                                       "Policy definition error", MessageBoxButton.OK,
                                       MessageBoxImage.Warning, MessageBoxResult.Cancel);
                return;

            }
            else if (functionalSpecComplete == false && groupfunctionalSpecComplete == true)
            {
                if (!(functionalParameters.Count() == 1))
                {
                    MessageBox.Show(this, "actor role/group expected.",
                                       "Policy definition error", MessageBoxButton.OK,
                                       MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }

                functionalParameters.Add(selected_regulatory_att);
                if (functionalParameters.Count() == 3)
                {
                    functionalAttributes_lb.IsEnabled = true;
                    functionalSpecComplete = true;
                    selected_regulatory_att = selected_regulatory_att + " )";
                    activeInactiveCompsLBSelection();
                    functionalParameters = new List<string>();
                }
                else
                {
                    selected_regulatory_att = selected_regulatory_att + " , ";
                }

                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_regulatory_att + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_regulatory_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_regulatory_att + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_regulatory_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_regulatory_att + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_regulatory_att);
                    comp_id = comp_id + 1;
                }
            }

            regulatoryAttributes_lb.SelectedIndex = -1;
        }

        private void agentAttributes_lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (agentAttributes_lb.SelectedItem == null)
            {
                return;
            }
            string selected_agent_att = agentAttributes_lb.SelectedItem.ToString();
            if (functionalSpecComplete == true && groupfunctionalSpecComplete ==true)
            {
                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_agent_att + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_agent_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_agent_att + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_agent_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_agent_att + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_agent_att);
                    comp_id = comp_id + 1;
                }

                string attribute_domain = "";
                List<string> att_dom_names = new List<string>();
                foreach (Attribute att in agentAttributes)
                {
                    if (att.name.Equals(selected_agent_att))
                    {
                        selectedAttribute = att;
                        isAgentAttSelected = true;
                        isFunctionalAttSelected = false;
                        isRegulatoryAttSelected = false;
                        isEnvironmentalAttSelected = false;
                        isActorRoleSelected = false;
                        isGroupSelected = false;
                        isGroupFunctionSelected = false;

                        //int i = 0;
                        foreach (string s in att.domain)
                        {
                            att_dom_names.Add(s);
                        }
                        break;
                    }
                }
                domain_l_t.Content = attribute_domain + " " + selectedAttribute.literalType;
                reloadDomainInComboBox(att_dom_names);
                activeInactiveCompsLBSelection();
            }
            else if (functionalSpecComplete == true && groupfunctionalSpecComplete == false)
            {
                MessageBox.Show(this, "group expected.",
                                       "Policy definition error", MessageBoxButton.OK,
                                       MessageBoxImage.Warning, MessageBoxResult.Cancel);
                return;

            }
            else if (functionalSpecComplete == false && groupfunctionalSpecComplete == true)
            {
                if (!(functionalParameters.Count() == 1))
                {
                    MessageBox.Show(this, "actor role/group expected.",
                                       "Policy definition error", MessageBoxButton.OK,
                                       MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }

                functionalParameters.Add(selected_agent_att);
                if (functionalParameters.Count() == 3)
                {
                    functionalAttributes_lb.IsEnabled = true;
                    functionalSpecComplete = true;
                    selected_agent_att = selected_agent_att + " )";
                    activeInactiveCompsLBSelection();
                    functionalParameters = new List<string>();
                }
                else
                {
                    selected_agent_att = selected_agent_att + " , ";
                }

                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_agent_att + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_agent_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_agent_att + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_agent_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_agent_att + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_agent_att);
                    comp_id = comp_id + 1;
                }
            }
            
            agentAttributes_lb.SelectedIndex = -1;
        }

        private void functionalAttributes_lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (functionalAttributes_lb.SelectedItem == null)
            {
                return;
            }

            //string selected_functional_att = functionalAttributes_lb.SelectedItem.ToString();
            ListBoxItem lbi = (ListBoxItem)functionalAttributes_lb.SelectedItem;
            string selected_functional_att = (string)lbi.Tag;

            if (functionalSpecComplete == true && groupfunctionalSpecComplete == true)
            {
                functionalSpecComplete = false;

                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_functional_att + " ( ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_functional_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_functional_att + " ( ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_functional_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_functional_att + " ( ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_functional_att);
                    comp_id = comp_id + 1;
                }

                string attribute_domain = "";
                List<string> att_dom_names = new List<string>();
                foreach (Attribute att in functionalAttributes)
                {
                    if (att.name.Equals(selected_functional_att))
                    {
                        selectedAttribute = att;
                        isAgentAttSelected = false;
                        isRegulatoryAttSelected = false;
                        isFunctionalAttSelected = true;
                        isEnvironmentalAttSelected = false;
                        isActorRoleSelected = false;
                        isGroupFunctionSelected = false;
                        isGroupSelected = false;

                        foreach (string s in att.domain)
                        {
                            att_dom_names.Add(s);
                        }
                        break;
                    }
                }
                domain_l_t.Content = attribute_domain + " " + selectedAttribute.literalType;
                reloadDomainInComboBox(att_dom_names);
                activeInactiveCompsLBSelection();

                functionalAttributes_lb.IsEnabled = false;
                functionalAttributes_lb.SelectedIndex = -1;    
            }
            else if (functionalSpecComplete == true && groupfunctionalSpecComplete == false)
            {
                MessageBox.Show(this, "group expected.",
                                        "Policy definition error", MessageBoxButton.OK,
                                        MessageBoxImage.Warning, MessageBoxResult.Cancel);
                return;
                
            }
      
        }

        private void environmentalAttributes_lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (environmentAttributes_lb.SelectedItem == null)
            {
                return;
            }

            string selected_env_att = environmentAttributes_lb.SelectedItem.ToString();
            if (functionalSpecComplete == true && groupfunctionalSpecComplete == true)
            {
                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_env_att + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_env_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_env_att + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_env_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_env_att + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_env_att);
                    comp_id = comp_id + 1;
                }

                string attribute_domain_long = "";
                string attribute_domain = "";
                List<string> att_dom_names = new List<string>();
                foreach (Attribute att in environmentalAttributes)
                {
                    if (att.name.Equals(selected_env_att))
                    {
                        selectedAttribute = att;
                        isAgentAttSelected = false;
                        isRegulatoryAttSelected = false;
                        isFunctionalAttSelected = false;
                        isEnvironmentalAttSelected = true;
                        isActorRoleSelected = false;
                        isGroupFunctionSelected = false;
                        isGroupSelected = false;

                        //int i = 0;
                        foreach (string s in att.domain)
                        {
                            att_dom_names.Add(s);
                        }
                        break;
                    }
                }
                domain_l_t.Content = attribute_domain + " " + selectedAttribute.literalType;
                domain_l_t.ToolTip = attribute_domain_long;
                reloadDomainInComboBox(att_dom_names);
                activeInactiveCompsLBSelection();
            }
            else if (functionalSpecComplete == true && groupfunctionalSpecComplete == false)
            {
                MessageBox.Show(this, "group expected.",
                                        "Policy definition error", MessageBoxButton.OK,
                                        MessageBoxImage.Warning, MessageBoxResult.Cancel);
                return;
                
            }
            else if (functionalSpecComplete == false && groupfunctionalSpecComplete == true)
            {
                if (!(functionalParameters.Count() == 1))
                {
                    MessageBox.Show(this, "actor role/group expected.",
                                       "Policy definition error", MessageBoxButton.OK,
                                       MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }
                functionalParameters.Add(selected_env_att);
                if (functionalParameters.Count() == 3)
                {
                    functionalAttributes_lb.IsEnabled = true;
                    functionalSpecComplete = true;
                    selected_env_att = selected_env_att + " ) ";
                    functionalParameters = new List<string>();
                    activeInactiveCompsLBSelection();
                }
                else
                {
                    selected_env_att = selected_env_att + " , ";
                }

                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_env_att + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_env_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_env_att + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_env_att);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_env_att + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_env_att);
                    comp_id = comp_id + 1;
                }
            }

            environmentAttributes_lb.SelectedIndex = -1;
        }

        private void actor_roles_lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (actor_roles_lb.SelectedItem == null)
            {
                return;
            }
            string selected_actorRole = actor_roles_lb.SelectedItem.ToString();

            if (functionalSpecComplete == true && groupfunctionalSpecComplete == true)
            {
                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_actorRole + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_actorRole);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_actorRole + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_actorRole);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_actorRole + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_actorRole);
                    comp_id = comp_id + 1;
                }
                selectedAttribute = null;
                isAgentAttSelected = false;
                isFunctionalAttSelected = false;
                isRegulatoryAttSelected = false;
                isEnvironmentalAttSelected = false;
                isActorRoleSelected = true;
                isGroupFunctionSelected = false;
                isGroupSelected = false;

                domain_l_t.Content = "Agent";
                reloadDomainInComboBox(agents);
                activeInactiveCompsLBSelection();
            }
            else if (functionalSpecComplete == true && groupfunctionalSpecComplete == false)
            {
                if (!(groupFunctionalParameters.Count() == 0))
                {
                    MessageBox.Show(this, "group expected.",
                                       "Policy definition error", MessageBoxButton.OK,
                                       MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }

                groupFunctionalParameters.Add(selected_actorRole);
                if (groupFunctionalParameters.Count() == 2)
                {
                    group_functions_lb.IsEnabled = true;
                    groupfunctionalSpecComplete = true;
                    selected_actorRole = selected_actorRole + " ) ";
                    groupFunctionalParameters = new List<string>();
                    activeInactiveCompsLBSelection();
                }
                else
                {
                    selected_actorRole = selected_actorRole + " , ";
                }

                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_actorRole + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_actorRole);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_actorRole + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_actorRole);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_actorRole + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_actorRole);
                    comp_id = comp_id + 1;
                }

            }
            else if(functionalSpecComplete == false && groupfunctionalSpecComplete == true)
            {
                if (functionalParameters.Count() == 1)
                {
                    MessageBox.Show(this, "agent/environmental attribute expected.",
                                       "Policy definition error", MessageBoxButton.OK,
                                       MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }
                functionalParameters.Add(selected_actorRole);
                if (functionalParameters.Count() == 3)
                {
                    functionalAttributes_lb.IsEnabled = true;
                    functionalSpecComplete = true;
                    selected_actorRole = selected_actorRole + " ) ";
                    functionalParameters = new List<string>();
                    activeInactiveCompsLBSelection();
                }
                else
                {
                    selected_actorRole = selected_actorRole + " , ";
                }

                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_actorRole + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_actorRole);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_actorRole + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_actorRole);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_actorRole + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_actorRole);
                    comp_id = comp_id + 1;
                }
            }
            actor_roles_lb.SelectedIndex = -1;
        }

        private void groups_lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (groups_lb.SelectedItem == null)
            {
                return;
            }
            string selected_group = (string)groups_lb.SelectedItem;

            if (functionalSpecComplete == true && groupfunctionalSpecComplete == true)
            {
                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_group + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_group);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_group + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_group);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_group + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_group);
                    comp_id = comp_id + 1;
                }
                selectedAttribute = null;
                isAgentAttSelected = false;
                isFunctionalAttSelected = false;
                isRegulatoryAttSelected = false;
                isEnvironmentalAttSelected = false;
                isActorRoleSelected = false;
                isGroupSelected = true;
                isGroupFunctionSelected = false;

                //domain_l_t.Content = "Group";                
                //reloadDomainInComboBox(groupNames);

                List<string> groupMembership = new List<string>();
                groupMembership.Add("true");
                groupMembership.Add("false");
                reloadDomainInComboBox(groupMembership);

                activeInactiveCompsLBSelection();
            }
            else if (functionalSpecComplete == true && groupfunctionalSpecComplete == false)
            {
                if (!(groupFunctionalParameters.Count() == 1))
                {
                    MessageBox.Show(this, "actor/agent role expected.",
                                       "Policy definition error", MessageBoxButton.OK,
                                       MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }

                groupFunctionalParameters.Add(selected_group);
                if (groupFunctionalParameters.Count() == 2)
                {
                    group_functions_lb.IsEnabled = true;
                    groupfunctionalSpecComplete = true;
                    selected_group = selected_group + " ) ";
                    groupFunctionalParameters = new List<string>();
                    activeInactiveCompsLBSelection();
                }
                else
                {
                    selected_group = selected_group + " , ";
                }

                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_group + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_group);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_group + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_group);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_group + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_group);
                    comp_id = comp_id + 1;
                }

            }
            else if (functionalSpecComplete == false && groupfunctionalSpecComplete == true)
            {
                if (functionalParameters.Count() == 1)
                {
                    MessageBox.Show(this, "agent/environmental attribute expected.",
                                       "Policy definition error", MessageBoxButton.OK,
                                       MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }
                functionalParameters.Add(selected_group);
                if (functionalParameters.Count() == 3)
                {
                    functionalAttributes_lb.IsEnabled = true;
                    functionalSpecComplete = true;
                    selected_group = selected_group + " ) ";
                    functionalParameters = new List<string>();
                    activeInactiveCompsLBSelection();
                }
                else
                {
                    selected_group = selected_group + " , ";
                }

                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_group + " ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_group);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_group + " ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_group);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_group + " ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_group);
                    comp_id = comp_id + 1;
                }
            }
            
            groups_lb.SelectedIndex = -1;
        }


        private void groupFunctional_lb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (group_functions_lb.SelectedItem == null)
            {
                return;
            }

            ListBoxItem l = (ListBoxItem)group_functions_lb.SelectedItem;
                        
            string selected_group_function = (string) l.Tag;

            if (functionalSpecComplete == true && groupfunctionalSpecComplete == true)
            {
                groupfunctionalSpecComplete = false;

                if (if_rc_rb.IsChecked == true)
                {
                    if_rc_tb.AppendText(selected_group_function + " ( ");
                    if_rc_formula.Add("attribute_" + comp_id, selected_group_function);
                    comp_id = comp_id + 1;
                }
                else if (if_then_rc_rb.IsChecked == true)
                {
                    if_then_rc_tb.AppendText(selected_group_function + " ( ");
                    if_then_rc_formula.Add("attribute_" + comp_id, selected_group_function);
                    comp_id = comp_id + 1;
                }
                else if (if_then_unless_rc_rb.IsChecked == true)
                {
                    if_then_unless_rc_tb.AppendText(selected_group_function + " ( ");
                    if_then_unless_rc_formula.Add("attribute_" + comp_id, selected_group_function);
                    comp_id = comp_id + 1;
                }

                string attribute_domain = "";
                List<string> att_dom_names = new List<string>();
                
                selectedAttribute = null;
                isAgentAttSelected = false;
                isFunctionalAttSelected = false;
                isRegulatoryAttSelected = false;
                isEnvironmentalAttSelected = false;
                isActorRoleSelected = false;
                isGroupSelected = false;
                isGroupFunctionSelected = true;

                domain_l_t.Content = "membershipFunction(Agent Role, group)";
                reloadDomainInComboBox(att_dom_names);
                activeInactiveCompsLBSelection();

                group_functions_lb.IsEnabled = false;
                group_functions_lb.SelectedIndex = -1;
            }
            else if (functionalSpecComplete == false && groupfunctionalSpecComplete == true)
            {
                MessageBox.Show(this, "Invalid selection.",
                                        "Policy definition error", MessageBoxButton.OK,
                                        MessageBoxImage.Warning, MessageBoxResult.Cancel);
                return;

            }

        }

        private void reloadDomainInComboBox(List<string> doms)
        {
            foreach (string dom in doms)
            {
                value_cb.Items.Add(dom);
            }
        }

        public void activeInactiveCompsLBSelection()
        {
            if (functionalSpecComplete == false || groupfunctionalSpecComplete == false)
            {
                return;
            }

            agentAttributes_lb.IsEnabled = false;
            environmentAttributes_lb.IsEnabled = false;
            regulatoryAttributes_lb.IsEnabled = false;
            functionalAttributes_lb.IsEnabled = false;
            actor_roles_lb.IsEnabled = false;
            //actor_roles_lb.ItemsSource = new List<string>();
            actor_roles_lb.IsEnabled = false;
            groups_lb.IsEnabled = false;
            group_functions_lb.IsEnabled = false;

            lessthan.IsEnabled = true;
            greaterthan.IsEnabled = true;
            equals.IsEnabled = true;
            notequals.IsEnabled = true;
            //properSubset.IsEnabled = true;
            //subset.IsEnabled = true;
            //union.IsEnabled = true;
            //intersection.IsEnabled = true;
            //elementOf.IsEnabled = true;
            //notElementof.IsEnabled = true;
            //not.IsEnabled = true;
            or.IsEnabled = true;
            and.IsEnabled = true;
            //implies.IsEnabled = true;
            //openingBracket.IsEnabled = true;
            //closingBracket.IsEnabled = true;
            plus.IsEnabled = true;
            minus.IsEnabled = true;
            multiplication.IsEnabled = true;
            division.IsEnabled = true;
            value_cb.IsEnabled = false;
            att_value_ok.IsEnabled = false;
        }
        

        public void activeInactiveCompsOk_b_Selection()
        {
            if (functionalSpecComplete == false || groupfunctionalSpecComplete == false)
            {
                return;
            }

            agentAttributes_lb.IsEnabled = false;
            environmentAttributes_lb.IsEnabled = false;
            regulatoryAttributes_lb.IsEnabled = false;
            functionalAttributes_lb.IsEnabled = false;
            actor_roles_lb.IsEnabled = false;
            //actor_roles_lb.ItemsSource = new List<string>();
            actor_roles_lb.IsEnabled = false;
            groups_lb.IsEnabled = false;
            group_functions_lb.IsEnabled = false;

            lessthan.IsEnabled = true;
            greaterthan.IsEnabled = true;
            equals.IsEnabled = true;
            notequals.IsEnabled = true;
            //properSubset.IsEnabled = true;
            //subset.IsEnabled = true;
            //union.IsEnabled = true;
            //intersection.IsEnabled = true;
            //elementOf.IsEnabled = true;
            //notElementof.IsEnabled = true;
            //not.IsEnabled = false;
            or.IsEnabled = false;
            and.IsEnabled = false;
            //implies.IsEnabled = true;
            //openingBracket.IsEnabled = true;
            //closingBracket.IsEnabled = true;
            plus.IsEnabled = true;
            minus.IsEnabled = true;
            multiplication.IsEnabled = true;
            division.IsEnabled = true;
            value_cb.IsEnabled = false;
            att_value_ok.IsEnabled = false;
        }

        private void Select_PolicyClose_Button_Click(object sender, RoutedEventArgs e)
        {
            if (ci_ != null)
                ci_.loadPolicyStatements();

            this.Close();
        }

        private void att_value_ok_Click(object sender, RoutedEventArgs e)
        {
            if (isAgentAttSelected == false && isFunctionalAttSelected == false && isRegulatoryAttSelected == false
                && isEnvironmentalAttSelected == false && isActorRoleSelected == false
                 && isGroupSelected == false && isGroupFunctionSelected == false)
            {
                MessageBox.Show(this, "You need to first select a constraint attribute/actor role.",
                    "Policy definition error", MessageBoxButton.OK,
                    MessageBoxImage.Warning, MessageBoxResult.Cancel);
                return;
            }

            String input_value = "";
            if (value_cb.SelectedItem != null)
            {
                input_value = value_cb.SelectedItem.ToString();
            }
            else
            {
                input_value = value_cb.Text;
            }

            if ((input_value == null) || input_value.Length == 0)
            {
                MessageBox.Show(this, "Undefined value of " + selectedAttribute.name + "!",
                                     "Policy definition error", MessageBoxButton.OK,
                                     MessageBoxImage.Warning, MessageBoxResult.Cancel);
                return;           
            }

            if(selectedAttribute == null && domain_l_t.Content.Equals("Agent"))
            {
                bool validAgent = false;
                foreach (string agent in agents)
                {
                    if (agent.Equals(input_value))
                    {
                        validAgent = true;
                        break;
                    }
                }

                if (!validAgent)
                {
                    MessageBox.Show(this, "invalid actor instance!",
                                     "Policy definition error", MessageBoxButton.OK,
                                     MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;  
                }
            }
            
            else if (selectedAttribute == null && domain_l_t.Content.Equals("Group"))
            {
                bool validGroup = false;
                foreach (string groupName in groupNames)
                {
                    if (groupName.Equals(input_value))
                    {
                        validGroup = true;
                        break;
                    }
                }

                if (!validGroup)
                {
                    MessageBox.Show(this, "invalid group instance!",
                                     "Policy definition error", MessageBoxButton.OK,
                                     MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }
            }

            else if (selectedAttribute!= null && selectedAttribute.literalType.Equals("[string]"))
            {
                bool compactible_value = false;
                foreach (string s in selectedAttribute.domain)
                {
                    if (input_value.Equals(s))
                    {
                        compactible_value = true;
                        break;
                    }
                }
                if (compactible_value == false)
                {
                    MessageBoxResult result = MessageBox.Show(this, "Value of " + selectedAttribute.name + "  is not in the list" +
                        "of defined domain values.\n Do you want to add this to the list?",
                            "Policy definition error", MessageBoxButton.YesNo,
                            MessageBoxImage.Information);

                    if (result == MessageBoxResult.No)
                    {
                        return;
                    }
                    else
                    {
                        selectedAttribute.addDomain(input_value);
                        MisUseAnObjectsDB.addAttributeDomain(selectedAttribute, input_value, MainWindow.clusterName);
                    }
                }
            }
            else if (selectedAttribute != null && selectedAttribute.literalType.Equals("[boolean]"))
            {
                bool num;
                bool compactible_value = bool.TryParse(input_value, out num);

                if (!compactible_value)
                {
                    MessageBox.Show(this, "value of attribute is incompactible with the defined domain",
                                        "Policy definition error", MessageBoxButton.OK,
                                        MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }
            }
            else if (selectedAttribute != null && selectedAttribute.literalType.Equals("[numeric]"))
            {
                double num;
                bool compactible_value = double.TryParse(input_value, out num);

                if (!compactible_value)
                {
                    MessageBox.Show(this, "value of attribute is incompactible with the defined domain",
                                         "Policy definition error", MessageBoxButton.OK,
                                          MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }
            }


            if (if_rc_rb.IsChecked == true)
            {
                if_rc_tb.AppendText(input_value + " ");
                if_rc_formula.Add("attribute_" + comp_id, input_value);
                comp_id = comp_id + 1;
            }
            else if (if_then_rc_rb.IsChecked == true)
            {
                if_then_rc_tb.AppendText(input_value + " ");
                if_then_rc_formula.Add("attribute_" + comp_id, input_value);
                comp_id = comp_id + 1;
            }
            else if (if_then_unless_rc_rb.IsChecked == true)
            {
                if_then_unless_rc_tb.AppendText(input_value + " ");
                if_then_unless_rc_formula.Add("attribute_" + comp_id, input_value);
                comp_id = comp_id + 1;
            }

            isAgentAttSelected = false;
            isRegulatoryAttSelected = false;
            isFunctionalAttSelected = false;
            isEnvironmentalAttSelected = false;
            isActorRoleSelected = false;
            isGroupSelected = false;
            isGroupFunctionSelected = false;

            value_cb.Items.Clear();
            value_cb.Text = "";
            domain_l_t.Content = "";
            activeInactiveCompsOk_b_Selection();
        }

        private void rc_rb_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton d_b = (RadioButton)sender;
            string tag_id = (string)d_b.Tag;
            
            if (tag_id.Equals("if"))
            {
                if_rule_active = true;

                if_rc_rb.IsEnabled = true;

                if_then_rc_rb.IsEnabled = true;  
                if_then_unless_rc_rb.IsEnabled = true;
                then_temporal_cb.IsEnabled = true;
                unless_temporal_cb.IsEnabled = true;

                if_rc_tb.IsEnabled = true;
                if_then_rc_tb.IsEnabled = false;
                if_then_unless_rc_tb.IsEnabled = false;
                
            }
            else if (tag_id.Equals("if_then"))
            {
                if_rc_rb.IsEnabled = true;

                if_then_rc_rb.IsEnabled = true;
                if_then_unless_rc_rb.IsEnabled = true;
                then_temporal_cb.IsEnabled = true;
                unless_temporal_cb.IsEnabled = true;
                
                if_rc_tb.IsEnabled = false;
                if_then_rc_tb.IsEnabled = true;
                if_then_unless_rc_tb.IsEnabled = false;
                
            }
            else if (tag_id.Equals("if_then_unless"))
            {
                TextRange textRange_if = new TextRange(if_rc_tb.Document.ContentStart,
                if_rc_tb.Document.ContentEnd);
                string formula_statement_if = textRange_if.Text;
                formula_statement_if = formula_statement_if.TrimEnd('\n');
                formula_statement_if = formula_statement_if.TrimEnd('\r');

                TextRange textRange_if_then = new TextRange(if_then_rc_tb.Document.ContentStart,
                if_then_rc_tb.Document.ContentEnd);
                string formula_statement_if_then = textRange_if_then.Text;
                formula_statement_if_then = formula_statement_if_then.TrimEnd('\n');
                formula_statement_if_then = formula_statement_if_then.TrimEnd('\r');

                if (formula_statement_if.Length > 0 && formula_statement_if_then.Length > 0)
                {
                    if_rc_rb.IsEnabled = true;

                    if_then_rc_rb.IsEnabled = true;
                    if_then_unless_rc_rb.IsEnabled = true;
                    then_temporal_cb.IsEnabled = true;
                    unless_temporal_cb.IsEnabled = true;
                    
                    if_rc_tb.IsEnabled = false;
                    if_then_rc_tb.IsEnabled = false;
                    if_then_unless_rc_tb.IsEnabled = true;
                }
                else
                {
                    if_then_unless_rc_rb.IsChecked = false;
                    MessageBox.Show(this, "missing if( ) then( ) prerequisite.",
                                        "Policy definition error", MessageBoxButton.OK,
                                        MessageBoxImage.Warning, MessageBoxResult.Cancel);
                    return;
                }
            }           
            reinitialiseActiveInactiveComps();

            if (tag_id.Equals("if"))
            {
                functionalAttributes_lb.IsEnabled = true;

            }
            else if (tag_id.Equals("if_then"))
            {
                functionalAttributes_lb.IsEnabled = false;

            }
            else if (tag_id.Equals("if_then_unless"))
            {
                functionalAttributes_lb.IsEnabled = false;

            }

        }

        private void new_group_function_b_Click(object sender, RoutedEventArgs e)
        {
            NewGroupFunctionWindow ncw = new NewGroupFunctionWindow();
            ncw.Owner = (Window)this.Parent;
            ncw.ShowDialog();

            reloadGroupFunction_lb();
        }
        private void new_policy_function_b_Click(object sender, RoutedEventArgs e)
        {
            NewPolicyFunctionWindow ncw = new NewPolicyFunctionWindow();
            ncw.Owner = (Window)this.Parent;
            ncw.ShowDialog();

            reloadPolicyFunction_lb();
        }


        public void reloadPolicyFunction_lb()
        {
            functionalAttributes_lb.Items.Clear();
            functionalAttributes.Clear();///temp measure

            List<string> policyFunctions = MisUseAnObjectsDB.loadAllPolicyFunctions(MainWindow.clusterName);
            foreach (string pf in policyFunctions)
            {
                ////temp measure
                Attribute att = new Attribute();
                att.name = pf;
                att.literalType = "[string]";
                att.category = "functionalAttribute";
                att.clusterName = MainWindow.clusterName;
                functionalAttributes.Add(att);
                ////
                
                ListBoxItem l = new ListBoxItem();
                StackPanel s = new StackPanel();
                s.Orientation = System.Windows.Controls.Orientation.Horizontal;

                ContentPresenter c1 = new ContentPresenter();
                c1.Content = pf;

                s.Children.Add(c1);

                //add context menu to delete group membership function

                ContextMenu cm = new System.Windows.Controls.ContextMenu();
                cm.Height = 64;
                cm.Width = 136;

                MenuItem cm_d = new MenuItem();
                cm_d.Header = "Delete";
                cm_d.Tag = pf;
                cm_d.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(del_policy_function_Click));
                cm_d.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_d.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_d.FontSize = 12;
                cm_d.Foreground = Brushes.DarkGreen;

                BitmapImage cm_d_image = new BitmapImage();
                cm_d_image.BeginInit();
                Uri cm_d_Uri = new Uri("/PMisuseAn;component/images/DeleteHS.png", UriKind.RelativeOrAbsolute);
                cm_d_image.UriSource = cm_d_Uri;
                cm_d_image.EndInit();

                Image cm_d_iconImage = new Image();
                cm_d_iconImage.Source = cm_d_image;
                cm_d.Icon = cm_d_iconImage;

                cm.Items.Add(cm_d);
                l.ContextMenu = cm;

                l.Content = s;
                l.Tag = pf;

                functionalAttributes_lb.Items.Add(l);
            }
        }

        public void reloadGroupFunction_lb()
        {
            group_functions_lb.Items.Clear();

            List<string> groupFunctions = MisUseAnObjectsDB.loadAllGroupFunctions(MainWindow.clusterName);
            foreach (string gf in groupFunctions)
            {
                ListBoxItem l = new ListBoxItem();
                StackPanel s = new StackPanel();
                s.Orientation = System.Windows.Controls.Orientation.Horizontal;

                ContentPresenter c1 = new ContentPresenter();
                c1.Content = gf;
                
                s.Children.Add(c1);

                //add context menu to delete group membership function

                ContextMenu cm = new System.Windows.Controls.ContextMenu();
                cm.Height = 64;
                cm.Width = 136;

                MenuItem cm_d = new MenuItem();
                cm_d.Header = "Delete";
                cm_d.Tag = gf;
                cm_d.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(del_group_function_Click));
                cm_d.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                cm_d.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
                cm_d.FontSize = 12;
                cm_d.Foreground = Brushes.DarkGreen;

                BitmapImage cm_d_image = new BitmapImage();
                cm_d_image.BeginInit();
                Uri cm_d_Uri = new Uri("/PMisuseAn;component/images/DeleteHS.png", UriKind.RelativeOrAbsolute);
                cm_d_image.UriSource = cm_d_Uri;
                cm_d_image.EndInit();

                Image cm_d_iconImage = new Image();
                cm_d_iconImage.Source = cm_d_image;
                cm_d.Icon = cm_d_iconImage;

                cm.Items.Add(cm_d);
                l.ContextMenu = cm;

                l.Content = s;
                l.Tag = gf;
                
                group_functions_lb.Items.Add(l);
            }
        }

        public void del_policy_function_Click(object sender, RoutedEventArgs e)
        {

            MessageBoxResult result = MessageBox.Show("Confirm delete...", "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.No)
            {
                return;
            }

            MenuItem d_b = (MenuItem)sender;
            string tag_id = (string)d_b.Tag;
            MisUseAnObjectsDB.deletePolicyFunctionDB(tag_id, MainWindow.clusterName);

            reloadPolicyFunction_lb();

        }

        public void del_group_function_Click(object sender, RoutedEventArgs e)
        {

            MessageBoxResult result = MessageBox.Show("Confirm delete...", "Delete", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.No)
            {
                return;
            }

            MenuItem d_b = (MenuItem)sender;
            string tag_id = (string)d_b.Tag;
            MisUseAnObjectsDB.deleteGroupFunctionDB(tag_id, MainWindow.clusterName);

            reloadGroupFunction_lb();

        }
    }
}
